package com.leps.nq.op.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import com.leps.nq.bu.entity.BuTeamCust;
import com.leps.nq.bu.service.IBuTeamCustService;
import com.leps.nq.common.aspect.Log;
import com.leps.nq.common.enums.BusinessType;
import com.leps.nq.common.excel.DoubleConverter;
import com.leps.nq.common.excel.ExcelPageReadListener2;
import com.leps.nq.common.util.FileUploadUtils;
import com.leps.nq.common.vo.PageVo;
import com.leps.nq.common.vo.R;
import com.leps.nq.common.vo.RBuilder;
import com.leps.nq.op.entity.OpReplenish;
import com.leps.nq.op.service.IOpMonthlyTaskService;
import com.leps.nq.op.service.IOpReplenishService;
import com.leps.nq.op.vo.ExcelImportReplenishVo;
import com.leps.nq.op.vo.ReplenishQueryModel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 补液日志表 前端控制器
 * </p>
 *
 * @author hex
 * @since 2022-05-22
 */
@RestController
@RequestMapping("/op/op-replenish")
@Api(tags = "补液日志管理")
public class OpReplenishController {
    @Autowired
    IOpReplenishService replenishService;
    @Autowired
    IOpMonthlyTaskService monthlyTaskService;
    @Autowired
    IBuTeamCustService teamCustService;

    @GetMapping
    @ApiOperation("补液日志列表")
    public R<PageVo<OpReplenish>> list(ReplenishQueryModel queryModel) {
        PageVo<OpReplenish> pageVo = this.replenishService.pageByQueryModel(queryModel);
        return RBuilder.ok(pageVo);
    }

    @GetMapping("/{id}")
    @ApiOperation("根据id查询补液日志")
    public R<OpReplenish> getById(@PathVariable Long id) {
        return RBuilder.ok(this.replenishService.getById(id));
    }

    @PostMapping
    @ApiOperation("新增补液日志")
    @Transactional
    @Log(title = "防腐补液日志", businessType = BusinessType.INSERT)
    public R<?> save(@RequestBody OpReplenish replenish) {
        // 补填队伍ID
        Integer custId = replenish.getCustId();
        if(ObjectUtil.isNotNull(custId)) {
            BuTeamCust tc = this.teamCustService.lambdaQuery().eq(BuTeamCust::getCustId, custId).one();
            if(ObjectUtil.isNotNull(tc)) replenish.setTeamId(tc.getTeamId());
        }
        this.replenishService.save(replenish);
        // 更新月度任务完成量
        Integer year = DateUtil.year(replenish.getReplenishTime());
        Integer month = DateUtil.month(replenish.getReplenishTime());
        Integer teamId = replenish.getTeamId();
        this.monthlyTaskService.updateCompletionByTeamIdAndYearMonth(teamId, year, month);
        return RBuilder.ok(null);
    }

    @PutMapping
    @ApiOperation("修改补液日志")
    @Transactional
    @Log(title = "防腐补液日志", businessType = BusinessType.UPDATE)
    public R<?> update(@RequestBody OpReplenish replenish) {
        // 补填队伍ID
        Integer custId = replenish.getCustId();
        if(ObjectUtil.isNotNull(custId)) {
            BuTeamCust tc = this.teamCustService.lambdaQuery().eq(BuTeamCust::getCustId, custId).one();
            if(ObjectUtil.isNotNull(tc)) replenish.setTeamId(tc.getTeamId());
        }
        this.replenishService.updateById(replenish);
        // 更新月度任务完成量
        Integer year = DateUtil.year(replenish.getReplenishTime());
        Integer month = DateUtil.month(replenish.getReplenishTime());
        Integer teamId = replenish.getTeamId();
        this.monthlyTaskService.updateCompletionByTeamIdAndYearMonth(teamId, year, month);
        return RBuilder.ok();
    }

    @DeleteMapping
    @ApiOperation("删除补液日志")
    @Transactional
    @Log(title = "防腐补液日志", businessType = BusinessType.DELETE)
    public R<?> remove(@RequestBody List<Long> replenishIds) {
        List<OpReplenish> list = this.replenishService.listByIds(replenishIds);
        this.replenishService.removeBatchByIds(replenishIds);
        for (OpReplenish replenish : list) {
            Date date = replenish.getReplenishTime();
            int year = DateUtil.year(date);
            int month = DateUtil.month(date);
            Integer teamId = replenish.getTeamId();
            this.monthlyTaskService.updateCompletionByTeamIdAndYearMonth(teamId, year, month);
        }
        return RBuilder.ok();
    }

    @PostMapping("/import-excel")
    @ApiOperation("批量导入excel补液记录")
    @Log(title = "防腐补液日志", businessType = BusinessType.IMPORT)
    @Transactional(rollbackFor = Exception.class)
    public R importExcel(MultipartFile file) throws IOException {
        if (file == null || file.isEmpty()) throw new RuntimeException("请上传excel文件");
        // 存储excel文件
        FileUploadUtils.uploadUseOriginFileName(file);
        // === 执行导入 ===
        ExcelPageReadListener2<ExcelImportReplenishVo> listener = new ExcelPageReadListener2<>(list -> {
            List<OpReplenish> entities = new ArrayList<>();
            for (ExcelImportReplenishVo vo : list) {
                OpReplenish entity = BeanUtil.toBean(vo, OpReplenish.class);
                Integer custId = entity.getCustId();
                // 补填队伍ID
                if(ObjectUtil.isNotNull(custId)) {
                    BuTeamCust tc  = this.teamCustService.lambdaQuery().eq(BuTeamCust::getCustId, custId).one();
                    if(ObjectUtil.isNotNull(tc)) entity.setTeamId(tc.getTeamId());
                }
                entities.add(entity);
            }
            this.replenishService.saveBatch(entities);
        });
        EasyExcel.read(file.getInputStream(), ExcelImportReplenishVo.class, listener).registerConverter(new DoubleConverter()).sheet().doRead();
        // 更新月度任务完成量
        this.monthlyTaskService.updateCompletionAfterImportExcel();
        return RBuilder.ok();
    }

}
